package cate.game.activity.mooncake;

import cate.common.table.activity.mooncake.row.MooncakeExchangeRow;
import cate.common.table.d.GDOperation;
import cate.common.util.GameResult;
import cate.game.activity.base.core.SubActivitySingle;
import cate.game.activity.mooncake.msg.MooncakeExchangeDataResp;
import cate.game.res.MixRes;
import cate.game.res.MixResItem;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;

import java.util.HashMap;
import java.util.Map;

public class MooncakeExchange extends SubActivitySingle<MooncakeActivity> {
    @NoteField("key:配置id，value：购买次数")
    public Map<Integer, Integer> exchangeMap;

    @Override
    public void initialize(MooncakeActivity parent) {
        super.initialize(parent);
        if (exchangeMap == null) {
            exchangeMap = new HashMap<>();
        }
    }

    public void excelCheck() {
        Map<Integer, MooncakeExchangeRow> configs = findConfigs();
        if (configs == null || configs.isEmpty()) {
            exchangeMap.clear();
            return;
        }
        exchangeMap.entrySet().removeIf(entry -> !configs.containsKey(entry.getKey()));
        for (MooncakeExchangeRow config : configs.values()) {
            if (!exchangeMap.containsKey(config.id)) {
                exchangeMap.put(config.id, 0);
            }
        }
    }

    public void onRoleEnd() {
        exchangeMap.clear();
    }

    public void noticeUpdate() {
        role.sendNow(new MooncakeExchangeDataResp(this));
    }

    @JsonIgnore
    private Map<Integer, MooncakeExchangeRow> findConfigs() {
        return role.getGame().table.mooncake.exchange.findConfigs(parent.configTid());
    }

    public GameResult<MooncakeExchange> buyItem(int tid, int num) {
        GameResult<MooncakeExchange> r = new GameResult<>();
        r.data = this;
        MooncakeExchangeRow row = findExchangeRow(tid);
        if (row == null) {
            return r.fail("奖励不存在");
        }
        int times = exchangeMap.get(tid);
            if (times > row.limit - num) {
                return r.fail("限购次数不足");
            }

        MixRes rewardRes = new MixRes(row.reward);
        if (rewardRes.isEmpty()) {
            return r.fail("奖励为空");
        }
        MixRes costRes = new MixRes(row.cost);
        if (!costRes.isEmpty()) {
            costRes.items.forEach(item -> item.num *= num);
            EcResult<MixResItem> r_res = costRes.consumeCheck(role, null);
            if (!r_res.ok()) {
                return r.fail(r_res.message);
            }
            costRes.consume(role);
        }
        rewardRes.addAndDialog(role, true, GDOperation.MOONCAKE_EXCHANGE_REWARD, tid);
        exchangeMap.put(tid, times + num);
        return r.success();
    }

    public MooncakeExchangeRow findExchangeRow(int tid) {
        return role.getGame().table.mooncake.exchange.get(tid);
    }
}
